#!/usr/bin/env python
# -*- coding: UTF-8 -*-

import subprocess
import sys
import os.path

def runCmd(cmd, out=1, remote_host="localhost", ssh_key=None, input=None):
    '''
    Allow user to run a shell command and return retcode, stderr and stdout
    @param out: 0 = no output, 1 = standard (default)
    2 = pipe (send the output to another command)
    @param input : can be the pipe output of another command (or a string ??)
    @param remote_host : If you specify a remote host, the command will be
    executed on a remote host using ssh.
    You can like this:
        hostname
        username@hostname
        hostname:port
        username@hostname:port
    If you don't specify a port, 22 will be used by default.
    If you don't specify a username, current username will be
    used by default.
    @param ssh_key : path of your public key
    If remote_host is set and ssh_key isn't specified, the ssh_key
    will be searched in "~/.ssh/id_dsa.pub" or "~/.ssh/id_rsa.pub".
    '''
    OUT = subprocess.PIPE
    ERR = subprocess.PIPE
    if out == 0:
        OUT = None
        ERR = None
    if remote_host != "localhost":
#        if ssh_key == None:
#            if os.path.exists(os.path.expanduser("~/.ssh/id_rsa.pub")):
#                ssh_key = os.path.expanduser("~/.ssh/id_rsa.pub")
#            elif os.path.exists("~/.ssh/id_dsa.pub"):
#                ssh_key = os.path.expanduser("~/.ssh/id_dsa.pub")
#            else:
#                print('no ssh key found, cannot run command on ' + remote_host)
#                sys.exit()
        cmd = 'ssh ' + remote_host + ' "' + cmd + '"'
    if input != None:
        process = subprocess.Popen(cmd, shell=True, stdout=OUT, stderr=ERR, stdin=input)
    else:
        process = subprocess.Popen(cmd, shell=True, stdout=OUT, stderr=ERR)
    if out == 2:
        output = process.stdout
        return(output)
    else:
        output = process.communicate()
        retcode = process.returncode
        return(retcode, output)
